package com.project.web.admin.utils.freemarker.method;

import com.project.web.admin.service.core.StdCodeService;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取标准编码显示的方法
 */
@Component("stdCodeMethod")
public class StdCodeMethod implements TemplateMethodModelEx {

    @Resource(name = "stdCodeServiceImpl")
    private StdCodeService stdCodeService;

    //保存在请求对象中的标准编码的对象
    private final String REQUEST_STDCODENAME_PREFIX = "request_stdcodename_";

    @SuppressWarnings({"rawtypes", "unchecked"})
    public Object exec(List arguments) throws TemplateModelException {
        if (arguments != null && !arguments.isEmpty() && arguments.size() == 2) {
            String codeType = arguments.get(0).toString();
            Object codeObj = arguments.get(1);

            if (codeObj == null) {
                return null;
            }
            String code = codeObj.toString();
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            Map<String, String> map = null;
            if (requestAttributes != null) {
                map = (LinkedHashMap<String, String>) requestAttributes.getAttribute(REQUEST_STDCODENAME_PREFIX + codeType, RequestAttributes.SCOPE_REQUEST);
                if (map == null) {
                    map = stdCodeService.getMap(codeType, true);
                    requestAttributes.setAttribute(REQUEST_STDCODENAME_PREFIX + codeType, map, RequestAttributes.SCOPE_REQUEST);
                }
            } else {
                map = stdCodeService.getMap(codeType, true);
            }

            return map == null ? null : map.get(code);
        }
        return null;
    }
}

